﻿// ********************************************************************
//  文件名: MyTcpListener.cs
//  描述:
//  作者: 胡宇辰
//  创建时间: 2024-3-18
// 
//  修改历史:
// ********************************************************************

using System.Collections.Concurrent;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace MyApp;

public class MyTcpListener
{
    static ConcurrentDictionary<EndPoint, TcpClient> clients = new ConcurrentDictionary<EndPoint, TcpClient>();
    static TcpListener tcpListener;
    public static void Start()
    {
        var serverIPEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 6324); // 当前服务器使用的ip和端口
        TcpListener tcpListener = new TcpListener(serverIPEndPoint);
        tcpListener.Start();
        Console.WriteLine("服务端已启用......"); // 阻塞线程的执行，直到一个客户端连接
        while (true)
        {
            var tcpClient = tcpListener.AcceptTcpClient();
            Console.WriteLine("Client已连接:" + tcpClient.Client.RemoteEndPoint);
            if (clients.TryAdd(tcpClient.Client.RemoteEndPoint, tcpClient))
            {
                var t1 = new Thread(ReceiveMsg!);
                t1.IsBackground = true;
                t1.Start(tcpClient);
            }
            else
            {
                tcpClient.Close();
            }
        }
    }
    
    static void ReceiveMsg(object o)
    {
        if(!(o is TcpClient client))
        {
            return;
        }
        var stream = client.GetStream();
        byte[] buffer = new byte[1024]; // 预设最大接受1024个字节长度，可修改
        byte[] sendBuffer = new byte[1024]; // 预设最大接受1024个字节长度，可修改
        int count = 0;
        try
        {
            while ((count = stream.Read(buffer, 0, buffer.Length)) != 0)
            {
                string stringData = Encoding.UTF8.GetString(buffer, 0, count);
                var str =
                    $"({DateTime.Now.ToString("yy-MM-dd hh:mm:ss")}){client.Client.RemoteEndPoint.ToString()}:{stringData}";
                Console.WriteLine(str);
                var sendCount = Encoding.UTF8.GetBytes(str, sendBuffer);
                foreach (var kv in clients)
                {
                    var clientStream = kv.Value.GetStream();
                    clientStream.Write(sendBuffer, 0, sendCount);
                }
            }
        }
        catch(Exception ex)
        {
            client.Dispose();
            Console.WriteLine(ex.Message);
        }
    }
}